package com.rslai.commons.validator.jsonvalidator.validators;

import com.rslai.commons.validator.jsonvalidator.matchers.JsonAssert;
import com.rslai.commons.validator.jsonvalidator.schema.Schema;

import java.util.ArrayList;
import java.util.List;

import static com.rslai.commons.validator.jsonvalidator.schema.Schema.getKey;

/**
 * JSON校验器，无序数组校验器
 */
public class DisorderValidator extends ArrayValidator {
    public static final String VALIDATOR_NAME = "disorder";

    /**
     * 构造函数
     * @param list list
     */
    public DisorderValidator(List<Object> list) {

    }

    /**
     * 数组校验
     * @param schemas schemas
     * @param actual 期望
     */
    @Override
    protected void arrayValidate(List<Schema<Object>> schemas, List<Object> actual) {
        if (schemas.size() == 0 && actual.size() != 0) {
            JsonAssert.fail("期望数组大小为 0，实际传入的是 " + actual.size(), getValueSchema().getOriginalSchemaStr(), actual);
        }
        for (Schema<Object> schema : schemas) {
            String errMsg = "";
            List<Integer> equalsSchema = new ArrayList<Integer>();
            boolean isValidate = false;
            for (int i = 0; i < actual.size(); i++) {
                if (!equalsSchema.contains(i)) {
                    try {
                        schema.validate(getKey(getCurrentKeyPath(), i), actual.get(i));
                    } catch (ClassCastException e) {
                        errMsg = e.getMessage();
                        continue;
                    } catch (AssertionError assertionError) {
                        errMsg = assertionError.getMessage();
                        continue;
                    }
                    errMsg = null;
                    isValidate = true;
                    equalsSchema.add(i);
                    break;
                }
            }
            if (!isValidate) {
                String message = String.format("列表无序对比失败 %s", errMsg);
                JsonAssert.fail(message, schema.getOriginalSchemaStr(), actual);
            }
        }
    }

    /**
     * 返回校验名称
     * @return 校验名称
     */
    @Override
    public String name() {
        return VALIDATOR_NAME;
    }
}
